using System;
using System.Collections.Generic;

namespace CSharpPro._1106;

public class Demo
{
    // User类，仅包含字段、属性和构造函数
    public class User
    {
        public string Username { get; set; }
        public string Password { get; set; }

        public User(string username, string password)
        {
            Username = username;
            Password = password;
        }
    }

    // 接口定义（在同一个类中通过内部接口实现）
    public interface IUserService
    {
        bool Register(User user, List<User> userList);
        User Login(string username, string password, List<User> userList);
    }

    // 接口实现类（在同一个类中通过内部类实现）
    public class UserService : IUserService
    {
        public bool Register(User user, List<User> userList)
        {
            foreach (var existingUser in userList)
            {
                if (existingUser.Username == user.Username)
                {
                    return false;
                }
            }
            userList.Add(user);
            return true;
        }

        public User Login(string username, string password, List<User> userList)
        {
            foreach (var user in userList)
            {
                if (user.Username == username && user.Password == password)
                {
                    return user;
                }
            }
            return null;
        }
    }

    public static void Main(string[] args)
    {
        // d. 创建泛型集合保存注册用户信息
        List<User> userList = new List<User>();
        IUserService userService = new UserService();

        // 注册测试
        User newUser = new User("test", "123456");
        bool registerResult = userService.Register(newUser, userList);
        Console.WriteLine(registerResult ? "注册成功" : "注册失败（用户名已存在）");

        // 登录测试
        User loggedInUser = userService.Login("test", "123456", userList);
        Console.WriteLine(loggedInUser != null ? "登录成功" : "登录失败（用户名或密码错误）");

        // e. 使用foreach循环进行数据迭代
        Console.WriteLine("当前用户列表：");
        foreach (var user in userList)
        {
            Console.WriteLine($"用户名：{user.Username}，密码：{user.Password}");
        }

        // e. 删除时使用for循环
        for (int i = 0; i < userList.Count; i++)
        {
            if (userList[i].Username == "test")
            {
                userList.RemoveAt(i);
                break;
            }
        }
        Console.WriteLine("删除后用户列表数量：" + userList.Count);
    }
}